package top.frsf.rpc.autoconfigure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.frsf.rpc.annotations.EnableRpcServer;
import top.frsf.rpc.autoconfigure.properties.RpcProperties;
import top.frsf.rpc.handler.RpcServiceInvokeHandler;
import top.frsf.rpc.registry.ServiceRegistry;
import top.frsf.rpc.server.NettyRpcServer;

/**
 * RPC 服务端自动配置类
 *
 * @author He Kuntao
 * @since 2025/7/9 10:03
 */
@Configuration
@ConditionalOnBean(annotation = EnableRpcServer.class)
public class RpcServerAutoConfiguration {
    /**
     * NettyRpcServer 条件装配
     *
     * @param rpcProperties RPC 配置
     * @param context       Spring 上下文
     * @return NettyRpcServer
     */
    @Bean
    public NettyRpcServer nettyRpcServer(RpcProperties rpcProperties,
                                         ApplicationContext context,
                                         ServiceRegistry registry) {
        RpcProperties.Server server = rpcProperties.getServer();
        return new NettyRpcServer(context, registry, server.getPort());
    }

    /**
     * RpcServiceInvokeHandler 条件装配
     *
     * @param context Spring 上下文
     * @return RpcServiceInvokeHandler
     */
    @Bean
    public RpcServiceInvokeHandler rpcServiceInvokeHandler(ApplicationContext context) {
        return new RpcServiceInvokeHandler(context);
    }
}
